﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Management.Automation;
using Amazon.EC2;
using Amazon.EC2.Model;
using System.Net;

namespace Readify.Management.Automation.Ec2
{
    [Cmdlet("Get", "Ec2Image")]
    public class GetEc2ImageCmdlet : Cmdlet
    {
        [Parameter(Mandatory = true)]
        public PSCredential Credential { get; set; }

        [Parameter()]
        public string[] Owner { get; set; }

        [Parameter()]
        public string[] ExecutableBy { get; set; }

        [Parameter()]
        public string[] ImageId { get; set; }

        protected override void ProcessRecord()
        {
            DescribeImagesRequest request = new DescribeImagesRequest();
            request = this.AppendOwnerModifierIfNecessary(request);
            request = this.AppendExecutableByIfNecessary(request);
            request = this.AppendImageIdIfNecessary(request);

            NetworkCredential credential = this.Credential.GetNetworkCredential();
            string key = credential.UserName;
            string secret = credential.Password;

            AmazonEC2 ec2 = new AmazonEC2Client(key, secret);
            DescribeImagesResponse response = ec2.DescribeImages(request);
            DescribeImagesResult result = response.DescribeImagesResult;

            foreach (Image image in result.Image)
            {
                this.WriteObject(image);
            }
        }

        private DescribeImagesRequest AppendExecutableByIfNecessary(DescribeImagesRequest request)
        {
            if (this.ExecutableBy == null)
            {
                return request;
            }

            request = request.WithExecutableBy(this.ExecutableBy);
            return request;
        }

        private DescribeImagesRequest AppendImageIdIfNecessary(DescribeImagesRequest request)
        {
            if (this.ImageId == null)
            {
                return request;
            }

            request = request.WithImageId(this.ImageId);
            return request;
        }

        private DescribeImagesRequest AppendOwnerModifierIfNecessary(DescribeImagesRequest request)
        {
            if (this.Owner == null)
            {
                return request;
            }

            request = request.WithOwner(this.Owner);
            return request;
        }
    }
}
